package com.ita.util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSourceFactory;


public class DBUtils {
	static Properties properties = new Properties();
	
	static DataSource dataSource = null;
	static boolean outputSQL=true;
	
	public static boolean isOutputSQL() {
		return outputSQL;
	}

	public static void setOutputSQL(boolean outputSQL) {
		DBUtils.outputSQL = outputSQL;
	}

	static {
		Context initContext;
		try {
			initContext = new InitialContext();
			try{
				Context envContext  = (Context)initContext.lookup("java:/comp/env");
				dataSource = (DataSource)envContext.lookup("jdbc/jmyoracle");
				System.out.println("[DBUtils]Load envContext DataSource OK!");
			}catch(Exception e){
				System.out.println("[DBUtils]Failed to load envContext DataSource,trying to read properties load DataSource.");
				InputStream is = DBUtils.class.getClassLoader().getResourceAsStream("amc.properties");
				try {
					properties.load(is);
					dataSource = BasicDataSourceFactory.createDataSource(properties);
					System.out.println("[DBUtils]Read properties load DataSource OK!");
				} catch (Exception e1) {
					System.out.println("[DBUtils]Read properties load DataSource Failed! "+e.getMessage());
				}
			}
		} catch (NamingException e) {
			//e.printStackTrace();
			System.out.println("[DBUtils]Init failed!"+e.getMessage());
		}
	}

	public static Connection getConnection() {
		Connection con = null;
		try {
			con = dataSource.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return con;
	}

	public static void free(Connection con, PreparedStatement ps, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (ps != null) {
				ps.close();
			}
			if (con != null) {
				con.close();
			}
		} catch (SQLException e) {
			//e.printStackTrace();
			System.out.println("[DBUtils]Free failed!"+e.getMessage());
		}
	}

}